package com.maxh.controller;

import com.alibaba.fastjson.JSONObject;
import com.maxh.annotation.AdminLoginToken;
import com.maxh.annotation.UserLoginToken;
import com.maxh.pojo.Admin;
import com.maxh.pojo.Teacher;
import com.maxh.pojo.User;
import com.maxh.service.LoginService;
import com.maxh.service.TokenService;
import com.maxh.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    LoginService loginService;
    @Autowired
    TokenService tokenService;

    // 管理员登录
    @RequestMapping("/training/login")
    public Object login(@RequestParam Map<String,Object> map, HttpServletResponse response) {
        return getObject(map, response,"admin");
    }

    // 讲师登录
    @RequestMapping("/training/teacher/login")
    public Object teacherLogin(@RequestParam Map<String,Object> map, HttpServletResponse response) {
        return getObject(map, response,"teacher");
    }
    // 学员登录
    @RequestMapping("/training/user/login")
    public Object userLogin(@RequestParam Map<String,Object> map, HttpServletResponse response) {
        return getObject(map, response,"user");
    }

    public Object getObject(@RequestParam Map<String, Object> map, HttpServletResponse response,String type) {
        JSONObject jsonObject = new JSONObject();
        System.out.println(map);
        if(map.get("userNum")==null|| map.get("password")==null){
            return  new ReturnError(401,"请求参数有误！");
        }else if(map.get("userNum").equals("")||map.get("password").equals("")){
            return  new ReturnError(403,"账号或密码为空！");
        }
        Boolean isLogin = false;
        String token =null;
        //MD5加密
        String passStr = MD5Util.getMD5((String) map.get("password"));
        System.out.println(passStr);
        if(type.equals("admin")){
        //管理员登录
            Admin admin = loginService.findByUserNum(map.get("userNum")+"");
            if(admin!=null){
                if(admin.getPassword().equals(passStr)){
                    isLogin = true;
                    token = tokenService.getAdminToken(admin);
                    jsonObject.put("user", admin);
                }
            }
        }else if(type.equals("teacher")){
            //讲师登录
            Teacher teacher = loginService.findByTeacherNum(map.get("userNum")+"");
            if(teacher!=null){
                if(teacher.getPassword().equals(passStr)){
                    isLogin = true;
                    token = tokenService.getTeacherToken(teacher);
                    jsonObject.put("user", teacher);
                }
            }
        }else{
            //学员登录
            User user = loginService.findByStudentNum(map.get("userNum")+"");
            if(user!=null){
                if(user.getPassword().equals(passStr)){
                    isLogin = true;
                    token = tokenService.getStudentToken(user);
                    jsonObject.put("user", user);
                }
            }
        }
        if (!isLogin) {
            return  new ReturnData(StatusCode.USER_AUTHENTICATION_ERROR,map,"账号或密码不正确！");
        } else {
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            jsonObject.put("token", token);
            System.out.println("登录成功返回的用户信息："+jsonObject);
            return  new ReturnData(StatusCode.REQUEST_SUCCESS, jsonObject, "后端数据交互正常！");
        }
    }

    /*修改密码*/
    @AdminLoginToken
    @PostMapping("/training/admin/password/update")
    public Object UpdateAdminPassword(@RequestParam("oldPassword") String oldPassword,@RequestParam("newPassword") String newPassword){
        String adminId = TokenUtil.getTokenAdminId();
        Admin admin = loginService.findAdminById(adminId);
        String oldPassMD5 = MD5Util.getMD5(oldPassword);
        System.out.println(oldPassMD5);
        if(!admin.getPassword().equals(oldPassMD5)){
            return new ReturnError(StatusCode.RETURN_ERROR,"原始密码错误！");
        }
        String newPassMD5 = MD5Util.getMD5(newPassword);
        Boolean isUpdate =  loginService.updateAdminPassword(adminId,newPassMD5);
        System.out.println("修改密码："+isUpdate);
        if(isUpdate){
            return new ReturnData(StatusCode.REQUEST_SUCCESS ,"密码修改成功！");
        }else{
            return new ReturnError(StatusCode.RETURN_ERROR,"密码修改失败！");
        }
    }

    /*修改密码*/
    @UserLoginToken
    @PostMapping("/training/user/password/update")
    public Object UpdateUserPassword(@RequestParam("oldPassword") String oldPassword,@RequestParam("newPassword") String newPassword){
        String userId = TokenUtil.getTokenUserId();
        User user = loginService.findUserById(userId);
        String oldPassMD5 = MD5Util.getMD5(oldPassword);
        if(!user.getPassword().equals(oldPassMD5)){
            return new ReturnError(StatusCode.RETURN_ERROR,"原始密码错误！");
        }
        String newPassMD5 = MD5Util.getMD5(newPassword);
        Boolean isUpdate =  loginService.updateUserPassword(userId,newPassMD5);
        System.out.println("修改密码："+isUpdate);
        if(isUpdate){
            return new ReturnData(StatusCode.REQUEST_SUCCESS ,"密码修改成功！");
        }else{
            return new ReturnError(StatusCode.RETURN_ERROR,"密码修改失败！");
        }
    }
}
